package org.exez.modules.visitor.controller;

import java.io.File;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.io.FileUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.*;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.exez.common.api.vo.Result;
import org.exez.common.aspect.annotation.AutoLog;
import org.exez.common.system.vo.LoginUser;
import org.exez.modules.system.entity.SysUser;
import org.exez.modules.system.service.ISysUserService;
import org.exez.modules.visitor.constant.AuthorityEnum;
import org.exez.modules.visitor.dto.ReservationApplicationDTO;
import org.exez.modules.visitor.entity.ReservationApplication;
import org.exez.modules.visitor.entity.VisitorAccessre;
import org.exez.modules.visitor.service.IVisitorAccessreService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.exez.common.system.base.controller.JeecgController;
import org.exez.modules.visitor.util.AES;
import org.exez.modules.visitor.vo.AccessRecordVo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

/**
 * @Description: 出入记录表
 * @Author: exez-boot
 * @Date:   2020-06-10
 * @Version: V1.0
 */
@Slf4j
@Api(tags="出入记录表")
@RestController
@RequestMapping("/visitor/visitorAccessre")
public class VisitorAccessreController extends JeecgController<VisitorAccessre, IVisitorAccessreService> {

	@Autowired
	private IVisitorAccessreService visitorAccessreService;

    @Autowired
    private ISysUserService userService;

    @Value("${url.mogo-view}")
    private String fileView;
	/*
	 * 分页列表查询
	 *
	 * @param visitorAccessre
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	@AutoLog(value = "出入记录表-分页列表查询")
	@ApiOperation(value="出入记录表-分页列表查询", notes="出入记录表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(VisitorAccessre visitorAccessre,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<VisitorAccessre> queryWrapper = QueryGenerator.initQueryWrapper(visitorAccessre, req.getParameterMap());
		Page<VisitorAccessre> page = new Page<VisitorAccessre>(pageNo, pageSize);
		IPage<VisitorAccessre> pageList = visitorAccessreService.page(page, queryWrapper);

		return Result.ok(pageList);
	}*/


     /**
      * 出入记录
      *
      * @param pageNo
      * @param pageSize
      * @return
      */
     @AutoLog(value = "出入记录表-分页列表查询")
     @ApiImplicitParams({
             @ApiImplicitParam(name = "startTime", value = "预约开始时间 :yyyy/MM/dd HH:mm:ss", required = false, dataType = "String", paramType = "query"),
             @ApiImplicitParam(name = "endTime", value = "预约结束时间:yyyy/MM/dd HH:mm:ss", required = false, dataType = "String", paramType = "query"),
             @ApiImplicitParam(name = "type", value = "进入方式1：车  2：人", required = false, dataType = "int", paramType = "query"),
             @ApiImplicitParam(name = "name", value = "姓名", required = false, dataType = "String", paramType = "query"),
             @ApiImplicitParam(name = "institutionId", value = "单位id", required = false, dataType = "Integer", paramType = "query"),
             @ApiImplicitParam(name = "personType", value = "人员类别 1.访客2.白名单3.警员4.黑名单", required = false, dataType = "int", paramType = "query"),
             @ApiImplicitParam(name = "pageNo", value = "页码", required = true, dataType = "Integer", paramType = "query"),
             @ApiImplicitParam(name = "pageSize", value = "页码大小", required = true, dataType = "Integer", paramType = "query"),
             @ApiImplicitParam(name = "accessMold", value = "0-进   1-出   空字符串-全部", required = true, dataType = "String", paramType = "query"),
     })
     @ApiOperation(value = "出入记录", notes = "出入记录")
     @GetMapping(value = "/listVisitorAccessre")
     public Result<IPage<VisitorAccessre>> listVisitorAccessre(
             @RequestParam(name = "startTime", required = false) String startTime,
             @RequestParam(name = "endTime", required = false) String endTime,
             @RequestParam(name = "type", required = false) Integer type,
             @RequestParam(name = "personType", required = false) Integer personType,
             @RequestParam(name = "name", required = false) String name,
             @RequestParam(name = "institutionId", required = false) Integer institutionId,
             @RequestParam(name = "pageNo" ,defaultValue="1") Integer pageNo,
             @RequestParam(name = "accessMold", required = false ) String accessMold,
             @RequestParam(name = "pageSize",defaultValue="10") Integer pageSize){
         Result<IPage<VisitorAccessre>> result = new Result<>();
         Page<VisitorAccessre> page = new Page<>(pageNo, pageSize);

         LambdaQueryWrapper<VisitorAccessre> queryWrapper = new LambdaQueryWrapper<>();
         queryWrapper.orderByDesc(VisitorAccessre::getAccessTime);

         LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
         if (null != institutionId) {
             queryWrapper.eq(VisitorAccessre::getInstitutionCode, institutionId);
         }else if (!AuthorityEnum.ONE_USER.getIndex().equals(sysUser.getAuthority())) {
             queryWrapper.in(VisitorAccessre::getInstitutionCode, AES.integerList(sysUser.getInstitutionId()));
         }

         if(StringUtils.isNotEmpty(startTime) && StringUtils.isNotEmpty(endTime)){
             queryWrapper.between(VisitorAccessre::getAccessTime, startTime.replaceAll("/","-"), endTime.replaceAll("/","-"));
         }
         if(StringUtils.isNotEmpty(name)){
             queryWrapper.eq(VisitorAccessre::getName, name);
         }
         if(type != null){
             queryWrapper.eq(VisitorAccessre::getAccessType, type);
         }
         if(StringUtils.isNotEmpty(accessMold)){
             queryWrapper.eq(VisitorAccessre::getAccessMold, accessMold);
         }
         if(personType != null){
             queryWrapper.eq(VisitorAccessre::getPersonType, personType);
         }
         IPage<VisitorAccessre> visitorAccessre = visitorAccessreService.listVisitorAccessre(page, queryWrapper);
         result.setSuccess(true);
         List<VisitorAccessre> records = visitorAccessre.getRecords();
         for (int i = 0; i < records.size(); i++) {
             VisitorAccessre accessre =  records.get(i);
             accessre.setAccessTime(accessre.getAccessTime().replaceAll("-","/"));
             accessre.setMobile(AES.mobileIdCard(accessre.getMobile()));
             accessre.setCertificatecardNo(AES.mobileIdCard(accessre.getCertificatecardNo()));
             accessre.setName(AES.nameXx(accessre.getName()));
             if(StringUtils.isNotEmpty(accessre.getAccessPhoto())){
                 accessre.setAccessPhoto(fileView + accessre.getAccessPhoto());
             }

             if(StringUtils.isNotEmpty(accessre.getCarPhoto())){
                 accessre.setCarPhoto(fileView + accessre.getCarPhoto());
             }

         }
         visitorAccessre.setRecords(records);
         result.setResult(visitorAccessre);
         return result;
     }

    /**
     * 出入车辆统计
     *
     * @return
     */
    @AutoLog(value = "出入车辆统计")

    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "1：周  2：月 3：年   white：内部车辆   notWhite：外部车辆 ", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "institutionId", value = "单位id", required = false, dataType = "Integer", paramType = "query"),
    })
    @ApiOperation(value = "出入车辆统计", notes = "出入车辆统计")
    @GetMapping(value = "/carData")
    public Result<Object> carData(@RequestParam(name = "institutionId", required = false) Integer institutionId,
            @RequestParam(name = "type", required = false) String type){
        Map<String, Object> map = new HashMap<>();
        List<Object> objects = visitorAccessreService.carData(Integer.parseInt(type),institutionId+"");

        return Result.ok(objects);
    }


    /**
     * 今日--出入车辆统计
     *
     * @return
     */
    @AutoLog(value = "今日--出入车辆统计")

    @ApiImplicitParams({
    })
    @ApiOperation(value = "今日--出入车辆统计", notes = "今日--出入车辆统计")
    @GetMapping(value = "/todayCarData")
    public Result<Object> todayCarData(){
        Map<String, Object> map = new HashMap<>();
        List<Object> objects = visitorAccessreService.todayCarData();

        return Result.ok(objects);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
    @AutoLog(value = "出入记录表-通过id查询")
    @ApiOperation(value="出入记录表-通过id查询", notes="出入记录表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
        VisitorAccessre visitorAccessre = visitorAccessreService.getById(id);
        return Result.ok(visitorAccessre);
    }*/

	/**
	 * 添加
	 *
	 * @param visitorAccessre
	 * @return
	 */
	@AutoLog(value = "出入记录表-添加")
	@ApiOperation(value="出入记录表-添加", notes="出入记录表-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody VisitorAccessre visitorAccessre) {
		visitorAccessreService.save(visitorAccessre);
		return Result.ok("添加成功！");
	}





    /**
     * 出入记录表-通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "出入记录表-通过id查询")
    @ApiOperation(value="出入记录表-通过id查询", notes="出入记录表-通过id查询测试")
    @ApiResponses({@ApiResponse(code = 200, message = "OK", response = ReservationApplicationDTO.class),})
    @GetMapping(value = "/getDetailsById")
    public Result<VisitorAccessre> getDetailsById(@RequestParam(name = "id", required = true) Integer id) {
        Result<VisitorAccessre> result = new Result<>();
        VisitorAccessre visitorAccessre = visitorAccessreService.getById(id);
        visitorAccessre.setMobile(AES.mobileIdCard(visitorAccessre.getMobile()));
        visitorAccessre.setCertificatecardNo(AES.mobileIdCard(visitorAccessre.getCertificatecardNo()));
        visitorAccessre.setName(AES.nameXx(visitorAccessre.getName()));
        if(StringUtils.isNotEmpty(visitorAccessre.getAccessPhoto())){
            visitorAccessre.setAccessPhoto(fileView + visitorAccessre.getAccessPhoto());
        }

        if(StringUtils.isNotEmpty(visitorAccessre.getCarPhoto())){
            visitorAccessre.setCarPhoto(fileView + visitorAccessre.getCarPhoto());
        }
        result.successSetDate(visitorAccessre);
        return result;
    }



  /**
   * 导出excel
   *
   * @param request
   * @param visitorAccessre
   */
  @RequestMapping(value = "/exportXls")
  public ModelAndView exportXls(HttpServletRequest request, VisitorAccessre visitorAccessre) {
      return super.exportXls(request, visitorAccessre, VisitorAccessre.class, "出入记录表");
  }



    /**
     * 出入记录表--定时任务
     *
     * @param
     * @return
     */
    @AutoLog(value = "出入记录表--定时任务")
    @ApiOperation(value="出入记录表--定时任务", notes="出入记录表--定时任务")
    @GetMapping(value = "/deleteMonthAccessRe")
    public Result<?> deleteMonthAccessRe() {
        visitorAccessreService.deleteMonthRecord();
        return null;
    }

}
